package service

import (
	"log"
	"testhttp/dao"
	"testhttp/model"
	"time"

	"github.com/kataras/iris/v12"
)

func ListDealer(params model.HttpParamsDealer) iris.Map {

	var query model.SelectDealer

	query.Where = "is_deleted = ?"
	query.Page = params.Page
	query.Pagesize = params.Pagesize
	if params.Dealer != "" {
		query.Where = query.Where + " and dealer like '%" + params.Dealer + "%'"
	}
	if params.Shop != "" {
		query.Where = query.Where + " and shop like '%" + params.Shop + "%'"
	}

	count, errcount := dao.CountDealer(query)
	res, errselect := dao.SelectDealer(query)

	if errcount != nil && errselect != nil {
		if errcount != nil {
			log.Print("Debug errcount:", errcount)
		}
		if errselect != nil {
			log.Print("Debug errselect:", errselect)
		}
		response := iris.Map{
			"code": 1,
			"msg":  "Fail"}
		return response
	} else {
		response := iris.Map{
			"code":  0,
			"msg":   "OK",
			"count": count,
			"data":  res}
		return response
	}

}

func UpdateDealer(data []model.Dealer) iris.Map {
	now := time.Now()
	for x := 0; x < len(data); x++ {
		data[x].UpdateTime = now
		if data[x].Remark == "" {
			data[x].Remark = " "
		}
	}
	valid, invalid := dao.UpdateDealer(data)

	response := iris.Map{
		"code": 0,
		// "msg":     "",
		"success": valid,
		"invalid": invalid,
	}
	return response
}

func AddDealer(data []model.Dealer) iris.Map {
	now := time.Now()
	for x := 0; x < len(data); x++ {
		// 初始化通用字段
		data[x].CreateTime = now
		data[x].UpdateTime = now
		data[x].IsDeleted = 0

	}
	err := dao.InsertDealer(data)
	if err != nil {
		res := iris.Map{
			"Code": 1,
			"Msg":  err.Error()}
		return res
	} else {
		res := iris.Map{
			"Code": 0,
			"Msg":  "OK"}
		return res
	}

}

func GetDealerbyId(id string) ([]model.Dealer, error) {
	var query model.SelectDealer

	query.Where = "is_deleted = ?"
	query.Page = 1
	query.Pagesize = 15
	query.Where = query.Where + " and dealer_uid = '" + id + "'"

	res, err := dao.SelectDealer(query)

	return res, err
}
